// mlStrategies.js - 存放机器学习策略相关函数
import { calculateRSI } from './strategies.js'

// ML特征计算函数
export const calculateMLFeatures = (data, index) => {
  if (index < 50) return null
  
  const currentData = data.slice(Math.max(0, index - 49), index + 1)
  const prices = currentData.map(d => d.close)
  const volumes = currentData.map(d => d.volume)
  const highs = currentData.map(d => d.high)
  const lows = currentData.map(d => d.low)
  
  const ma5 = calculateSMA(prices, 5)
  const ma10 = calculateSMA(prices, 10)
  const ma20 = calculateSMA(prices, 20)
  const ma50 = calculateSMA(prices, 50)
  
  const rsi = calculateRSI(currentData, 14)
  const macd = calculateMACD(prices)
  const bb = calculateBB(prices, 20, 2)
  const atr = calculateATR(currentData, 14)
  
  const volumeMA = calculateSMA(volumes, 20)
  const volumeRatio = volumes[volumes.length - 1] / (volumeMA[volumeMA.length - 1] || 1)
  
  const momentum = (prices[prices.length - 1] - prices[prices.length - 10]) / prices[prices.length - 10]
  const volatility = calculateVolatility(prices, 20)
  const supportResistance = calculateSupportResistance(currentData)
  
  return {
    price: prices[prices.length - 1],
    ma5: ma5[ma5.length - 1],
    ma10: ma10[ma10.length - 1],
    ma20: ma20[ma20.length - 1],
    ma50: ma50[ma50.length - 1],
    rsi: rsi[rsi.length - 1],
    macd_line: macd.macd[macd.macd.length - 1],
    macd_signal: macd.signal[macd.signal.length - 1],
    macd_histogram: macd.histogram[macd.histogram.length - 1],
    bb_upper: bb.upper[bb.upper.length - 1],
    bb_middle: bb.middle[bb.middle.length - 1],
    bb_lower: bb.lower[bb.lower.length - 1],
    atr: atr[atr.length - 1],
    volume_ratio: volumeRatio,
    momentum: momentum,
    volatility: volatility,
    support: supportResistance.support,
    resistance: supportResistance.resistance
  }
}

// ML辅助函数（简化实现）
export const calculateSMA = (data, period) => {
  const result = []
  for (let i = period - 1; i < data.length; i++) {
    let sum = 0
    for (let j = 0; j < period; j++) {
      sum += data[i - j]
    }
    result.push(sum / period)
  }
  return result
}

export const calculateMACD = (prices) => {
  const ema12 = calculateEMA(prices, 12)
  const ema26 = calculateEMA(prices, 26)
  const macd = ema12.map((val, i) => val - ema26[i])
  const signal = calculateEMA(macd, 9)
  
  return {
    macd: macd,
    signal: signal,
    histogram: macd.map((val, i) => val - signal[i])
  }
}

export const calculateEMA = (data, period) => {
  const result = []
  const multiplier = 2 / (period + 1)
  
  for (let i = 0; i < data.length; i++) {
    if (i === 0) {
      result.push(data[i])
    } else {
      result.push((data[i] - result[i - 1]) * multiplier + result[i - 1])
    }
  }
  
  return result
}

export const calculateBB = (prices, period, stdDevMultiplier) => {
  const result = []
  
  for (let i = period - 1; i < prices.length; i++) {
    // 计算中轨（移动平均线）
    let sum = 0
    for (let j = 0; j < period; j++) {
      sum += prices[i - j]
    }
    const middle = sum / period
    
    // 计算标准差
    let variance = 0
    for (let j = 0; j < period; j++) {
      const diff = prices[i - j] - middle
      variance += diff * diff
    }
    const stdDev = Math.sqrt(variance / period)
    
    // 计算上下轨
    const upper = middle + (stdDev * stdDevMultiplier)
    const lower = middle - (stdDev * stdDevMultiplier)
    
    result.push({ upper, middle, lower })
  }
  
  return result
}

export const calculateATR = (data, period) => {
  const tr = []
  
  for (let i = 1; i < data.length; i++) {
    const high = data[i].high
    const low = data[i].low
    const close = data[i].close
    const prevClose = data[i - 1].close
    
    const tr1 = high - low
    const tr2 = Math.abs(high - prevClose)
    const tr3 = Math.abs(low - prevClose)
    
    tr.push(Math.max(tr1, tr2, tr3))
  }
  
  return calculateSMA(tr, period)
}

export const calculateVolatility = (prices, period) => {
  const logReturns = []
  
  for (let i = 1; i < prices.length; i++) {
    const logReturn = Math.log(prices[i] / prices[i - 1])
    logReturns.push(logReturn)
  }
  
  const variance = logReturns.reduce((sum, val) => sum + val * val, 0) / logReturns.length
  return Math.sqrt(variance) * Math.sqrt(period)
}

export const calculateSupportResistance = (data) => {
  const prices = data.map(d => d.close)
  const highs = data.map(d => d.high)
  const lows = data.map(d => d.low)
  
  const support = Math.min(...lows)
  const resistance = Math.max(...highs)
  
  return { support, resistance }
}

export const calculateTrendSlope = (prices) => {
  if (prices.length < 2) return 0
  
  let sumX = 0, sumY = 0, sumXY = 0, sumXX = 0
  const n = prices.length
  
  for (let i = 0; i < n; i++) {
    sumX += i
    sumY += prices[i]
    sumXY += i * prices[i]
    sumXX += i * i
  }
  
  const slope = (n * sumXY - sumX * sumY) / (n * sumXX - sumX * sumX)
  return slope / (sumY / n) // 标准化斜率
}

export const identifyMarketState = (data, index) => {
  const lookback = Math.min(50, index)
  const recentData = data.slice(index - lookback + 1, index + 1)
  const prices = recentData.map(d => d.close)
  
  const trendSlope = calculateTrendSlope(prices)
  const volatility = calculateVolatility(prices, Math.min(20, prices.length))
  
  if (Math.abs(trendSlope) < 0.001 && volatility < 0.02) {
    return 'sideways'
  } else if (trendSlope > 0.002) {
    return 'bull'
  } else if (trendSlope < -0.002) {
    return 'bear'
  } else {
    return 'neutral'
  }
}

// 优化：ML预测算法（增强版）
export const performMLPrediction = (features, marketState, settings) => {
  const weights = getFeatureWeights(settings.mlFeatureWeighting)
  
  let buyScore = 0
  let sellScore = 0
  
  // 1. 趋势因子（增强版）
  const trendScore = calculateTrendScore(features)
  buyScore += trendScore.bullish * weights.trend
  sellScore += trendScore.bearish * weights.trend
  
  // 2. 动量因子（多层次）
  const momentumScore = calculateMomentumScore(features)
  buyScore += momentumScore.bullish * weights.momentum
  sellScore += momentumScore.bearish * weights.momentum
  
  // 3. 反转因子（精细化）
  const reversalScore = calculateReversalScore(features)
  buyScore += reversalScore.bullish * weights.reversal
  sellScore += reversalScore.bearish * weights.reversal
  
  // 4. 成交量因子（新增）
  const volumeScore = calculateVolumeScore(features)
  buyScore += volumeScore.bullish * weights.volume
  sellScore += volumeScore.bearish * weights.volume
  
  // 5. 波动性因子（新增）
  const volatilityScore = calculateVolatilityScore(features)
  buyScore += volatilityScore.adjustment
  sellScore -= volatilityScore.adjustment
  
  // 6. 市场状态调整（优化）
  const stateMultiplier = getMarketStateMultiplier(marketState, features)
  buyScore *= stateMultiplier.buy
  sellScore *= stateMultiplier.sell
  
  // 7. 情绪指标调整（增强）
  const sentimentFactor = calculateAdvancedSentimentIndicator(features, marketState)
  buyScore += sentimentFactor * settings.mlSentimentWeight
  sellScore -= sentimentFactor * settings.mlSentimentWeight
  
  // 8. 正则化评分（改进）
  const totalScore = Math.abs(buyScore) + Math.abs(sellScore)
  let normalizedBuyScore = totalScore > 0 ? Math.abs(buyScore) / totalScore : 0.5
  let normalizedSellScore = totalScore > 0 ? Math.abs(sellScore) / totalScore : 0.5
  
  // 9. 信号筛选和置信度计算
  let signal = 'hold'
  let confidence = 0
  
  const signalThreshold = 0.55 // 降低阈值提高灵敏度
  const strongSignalThreshold = 0.7 // 强信号阈值
  
  if (normalizedBuyScore > signalThreshold && normalizedBuyScore > normalizedSellScore) {
    signal = 'buy'
    confidence = normalizedBuyScore
    // 强信号额外加分
    if (normalizedBuyScore > strongSignalThreshold) {
      confidence = Math.min(0.95, confidence * 1.1)
    }
  } else if (normalizedSellScore > signalThreshold && normalizedSellScore > normalizedBuyScore) {
    signal = 'sell'
    confidence = normalizedSellScore
    // 强信号额外加分
    if (normalizedSellScore > strongSignalThreshold) {
      confidence = Math.min(0.95, confidence * 1.1)
    }
  }
  
  return {
    signal,
    confidence,
    buyScore: normalizedBuyScore,
    sellScore: normalizedSellScore,
    marketState,
    details: { // 新增：详细信息
      trendScore,
      momentumScore,
      reversalScore,
      volumeScore,
      volatilityScore,
      sentimentFactor
    }
  }
}

// 新增：趋势评分算法
export const calculateTrendScore = (features) => {
  let bullish = 0
  let bearish = 0
  
  // 多层MA分析
  const maAlignment = {
    short: features.price > features.ma5 ? 1 : -1,
    medium: features.ma5 > features.ma20 ? 1 : -1,
    long: features.ma20 > features.ma50 ? 1 : -1
  }
  
  // MA排列评分
  const alignmentScore = (maAlignment.short + maAlignment.medium + maAlignment.long) / 3
  if (alignmentScore > 0.33) bullish += 0.4
  if (alignmentScore < -0.33) bearish += 0.4
  
  // 价格位置分析
  const pricePosition = {
    aboveMA5: (features.price - features.ma5) / features.ma5,
    aboveMA20: (features.price - features.ma20) / features.ma20
  }
  
  if (pricePosition.aboveMA5 > 0.02) bullish += 0.3
  if (pricePosition.aboveMA5 < -0.02) bearish += 0.3
  if (pricePosition.aboveMA20 > 0.05) bullish += 0.3
  if (pricePosition.aboveMA20 < -0.05) bearish += 0.3
  
  return { bullish, bearish }
}

// 新增：动量评分算法
export const calculateMomentumScore = (features) => {
  let bullish = 0
  let bearish = 0
  
  // 价格动量
  if (features.momentum > 0.03) bullish += 0.5
  else if (features.momentum > 0.01) bullish += 0.3
  if (features.momentum < -0.03) bearish += 0.5
  else if (features.momentum < -0.01) bearish += 0.3
  
  // RSI动量
  if (features.rsi < 25) bullish += 0.4
  else if (features.rsi < 35) bullish += 0.2
  if (features.rsi > 75) bearish += 0.4
  else if (features.rsi > 65) bearish += 0.2
  
  // MACD动量
  if (features.macd_line > features.macd_signal && features.macd_histogram > 0) bullish += 0.3
  if (features.macd_line < features.macd_signal && features.macd_histogram < 0) bearish += 0.3
  
  // MACD金叉死叉加分
  const macdCrossover = features.macd_histogram > 0 && Math.abs(features.macd_histogram) > Math.abs(features.macd_line) * 0.1
  if (macdCrossover && features.macd_line > 0) bullish += 0.2
  if (!macdCrossover && features.macd_line < 0) bearish += 0.2
  
  return { bullish, bearish }
}

// 新增：反转评分算法
export const calculateReversalScore = (features) => {
  let bullish = 0
  let bearish = 0
  
  // 布林带位置
  const bbPosition = (features.price - features.bb_lower) / (features.bb_upper - features.bb_lower)
  if (bbPosition < 0.15) bullish += 0.6 // 接近下轨
  else if (bbPosition < 0.25) bullish += 0.3
  if (bbPosition > 0.85) bearish += 0.6 // 接近上轨
  else if (bbPosition > 0.75) bearish += 0.3
  
  // 支撑阻力分析
  const supportDistance = (features.price - features.support) / features.support
  const resistanceDistance = (features.resistance - features.price) / features.price
  
  if (supportDistance < 0.015) bullish += 0.4 // 靠近支撑
  if (resistanceDistance < 0.015) bearish += 0.4 // 靠近阻力
  
  // 极端指标值
  if (features.rsi < 15) bullish += 0.5 // 极度超卖
  if (features.rsi > 85) bearish += 0.5 // 极度超买
  
  return { bullish, bearish }
}

// 新增：成交量评分算法
export const calculateVolumeScore = (features) => {
  let bullish = 0
  let bearish = 0
  
  // 成交量放大程度
  if (features.volume_ratio > 2.5) {
    bullish += 0.4 // 大量放大通常是看涨信号
  } else if (features.volume_ratio > 1.8) {
    bullish += 0.2
  } else if (features.volume_ratio < 0.5) {
    bearish += 0.2 // 成交量萝缩可能是下跌信号
  }
  
  // 成交量与价格变化的关系
  if (features.volume_ratio > 1.5 && features.momentum > 0) {
    bullish += 0.3 // 量价齐升
  }
  
  if (features.volume_ratio > 1.5 && features.momentum < 0) {
    bearish += 0.3 // 量增价跌
  }
  
  return { bullish, bearish }
}

// 新增：波动性评分算法
export const calculateVolatilityScore = (features) => {
  let adjustment = 0
  
  // 波动性调整（低波动性适合交易，高波动性需谨慎）
  if (features.volatility < 0.015) {
    adjustment = 0.1 // 低波动性增加信心
  } else if (features.volatility > 0.08) {
    adjustment = -0.2 // 高波动性减少信心
  } else if (features.volatility > 0.05) {
    adjustment = -0.1
  }
  
  return { adjustment }
}

// 新增：市场状态乘数
export const getMarketStateMultiplier = (marketState, features) => {
  switch (marketState) {
    case 'bull':
      return { buy: 1.3, sell: 0.7 }
    case 'bear':
      return { buy: 0.6, sell: 1.4 }
    case 'sideways':
      // 震荡市适合反转交易
      return features.rsi < 30 || features.rsi > 70 ? 
        { buy: 1.1, sell: 1.1 } : { buy: 0.9, sell: 0.9 }
    default:
      return { buy: 1.0, sell: 1.0 }
  }
}

// 优化：高级情绪指标
export const calculateAdvancedSentimentIndicator = (features, marketState) => {
  let sentiment = 0
  
  // 1. 恐慌指数（VIX类似）
  const fearIndex = calculateFearIndex(features)
  if (fearIndex > 0.8) sentiment += 0.6 // 极度恐慌时反向买入
  else if (fearIndex > 0.6) sentiment += 0.3
  
  // 2. 贪婪指数
  const greedIndex = calculateGreedIndex(features)
  if (greedIndex > 0.8) sentiment -= 0.6 // 极度贪婪时谨慎
  else if (greedIndex > 0.6) sentiment -= 0.3
  
  // 3. 技术指标远离平衡
  const technicalExtreme = calculateTechnicalExtreme(features)
  sentiment += technicalExtreme * 0.4
  
  // 4. 市场状态调整
  if (marketState === 'bear' && sentiment > 0) {
    sentiment *= 1.2 // 熊市中的反转信号更强
  } else if (marketState === 'bull' && sentiment < 0) {
    sentiment *= 1.2 // 牛市中的顶部信号更强
  }
  
  return Math.max(-1, Math.min(1, sentiment))
}

// 恐慌指数计算
export const calculateFearIndex = (features) => {
  let fearScore = 0
  
  // RSI极低值
  if (features.rsi < 20) fearScore += 0.4
  else if (features.rsi < 30) fearScore += 0.2
  
  // 价格远低于布林带下轨
  if (features.price < features.bb_lower * 0.98) fearScore += 0.3
  
  // 高波动性环境
  if (features.volatility > 0.06) fearScore += 0.3
  
  return Math.min(1, fearScore)
}

// 贪婪指数计算
export const calculateGreedIndex = (features) => {
  let greedScore = 0
  
  // RSI极高值
  if (features.rsi > 80) greedScore += 0.4
  else if (features.rsi > 70) greedScore += 0.2
  
  // 价格远高于布林带上轨
  if (features.price > features.bb_upper * 1.02) greedScore += 0.3
  
  // 成交量异常放大
  if (features.volume_ratio > 3) greedScore += 0.3
  
  return Math.min(1, greedScore)
}

// 技术指标远离平衡
export const calculateTechnicalExtreme = (features) => {
  let extremeScore = 0
  
  // 多个指标同时超买/超卖
  const oversoldCount = [
    features.rsi < 25,
    features.price < features.bb_lower,
    features.momentum < -0.05
  ].filter(Boolean).length
  
  const overboughtCount = [
    features.rsi > 75,
    features.price > features.bb_upper,
    features.momentum > 0.05
  ].filter(Boolean).length
  
  if (oversoldCount >= 2) extremeScore += 0.5
  if (overboughtCount >= 2) extremeScore -= 0.5
  
  return extremeScore
}

// 保留原有的getFeatureWeights函数（并优化）
export const getFeatureWeights = (mode) => {
  switch (mode) {
    case 'trend_focused':
      return { trend: 0.5, momentum: 0.2, reversal: 0.2, volume: 0.1 }
    case 'momentum_focused':
      return { trend: 0.2, momentum: 0.5, reversal: 0.2, volume: 0.1 }
    case 'reversal_focused':
      return { trend: 0.2, momentum: 0.2, reversal: 0.5, volume: 0.1 }
    case 'balanced':
    default:
      return { trend: 0.3, momentum: 0.3, reversal: 0.3, volume: 0.1 }
  }
}

// 新增：风险评估函数
export const evaluateRiskConditions = (features, marketState, consecutiveLosses, cash, initialCapital) => {
  let allowBuy = true
  let forceSell = false
  
  // 1. 连续亏损风险控制
  if (consecutiveLosses >= 3) {
    allowBuy = false // 连续3次亏损后暂停交易
  }
  
  // 2. 资金水位风险控制
  const remainingCapitalRatio = cash / initialCapital
  if (remainingCapitalRatio < 0.3) {
    allowBuy = false // 资金低于30%暂停交易
  }
  
  // 3. 极端市场环境风险控制
  if (features.volatility > 0.1 && marketState === 'bear') {
    allowBuy = false // 高波动性熊市环境下不交易
    forceSell = true // 强制清仓
  }
  
  // 4. 技术指标极端值风险控制
  if (features.rsi > 90 || features.rsi < 10) {
    if (features.rsi > 90) forceSell = true
    if (features.rsi < 10) allowBuy = false // 极度超卖时谨慎交易
  }
  
  return { allowBuy, forceSell }
}

// 优化：动态仓位管理函数（考虑连续亏损）
export const calculateDynamicPosition = (features, prediction, basePercent, consecutiveLosses = 0) => {
  let positionMultiplier = 1
  
  // 基于置信度调整
  positionMultiplier *= prediction.confidence
  
  // 基于波动性调整
  if (features.volatility > 0.05) {
    positionMultiplier *= 0.6 // 更保守
  } else if (features.volatility < 0.02) {
    positionMultiplier *= 1.4 // 更激进
  }
  
  // 基于连续亏损调整
  if (consecutiveLosses > 0) {
    positionMultiplier *= Math.pow(0.8, consecutiveLosses) // 逐次减少仓位
  }
  
  // 基于市场状态调整
  if (features.volume_ratio > 2.0) {
    positionMultiplier *= 1.2 // 成交量放大时适度增加
  }
  
  return Math.max(3, Math.min(40, basePercent * positionMultiplier)) // 调整范围
}

export const calculateAdaptiveStopLoss = (atr, multiplier) => {
  return atr * multiplier / 100
}

export const calculateAdaptiveTakeProfit = (atr, confidence) => {
  const baseMultiplier = 2
  const confidenceMultiplier = confidence * 2
  return atr * (baseMultiplier + confidenceMultiplier) / 100
}

export const checkMLStopConditions = (currentPrice, lastBuyPrice, adaptiveStopLoss, adaptiveTakeProfit) => {
  if (!lastBuyPrice) return false
  
  const stopLossPrice = lastBuyPrice * (1 - adaptiveStopLoss)
  const takeProfitPrice = lastBuyPrice * (1 + adaptiveTakeProfit)
  
  return currentPrice <= stopLossPrice || currentPrice >= takeProfitPrice
}

// 新增：策略性能分析函数
export const calculateStrategyPerformance = (results) => {
  const trades = results.trades || []
  const signals = results.signals || []
  const equityCurve = results.equityCurve || []
  
  if (trades.length === 0) return {}
  
  // 信号质量分析
  const signalQuality = {
    totalSignals: signals.length,
    avgConfidence: signals.length > 0 ? signals.reduce((sum, s) => sum + (s.confidence || 0), 0) / signals.length : 0,
    strongSignals: signals.filter(s => s.confidence > 0.8).length,
    weakSignals: signals.filter(s => s.confidence < 0.6).length
  }
  
  // 交易效率分析
  const sellTrades = trades.filter(t => t.type === 'sell' && t.profit !== undefined)
  const profitableTrades = sellTrades.filter(t => t.profit > 0)
  
  const efficiency = {
    signalToTradeRatio: trades.length / Math.max(signals.length, 1),
    profitableTradeRatio: profitableTrades.length / Math.max(sellTrades.length, 1),
    avgHoldingPeriod: calculateAvgHoldingPeriod(trades),
    maxConsecutiveWins: calculateMaxConsecutive(sellTrades, true),
    maxConsecutiveLosses: calculateMaxConsecutive(sellTrades, false)
  }
  
  // 风险指标
  const riskMetrics = {
    maxDrawdown: calculateMaxDrawdownFromCurve(equityCurve),
    volatility: calculateEquityVolatility(equityCurve),
    riskAdjustedReturn: calculateRiskAdjustedReturn(equityCurve)
  }
  
  return {
    signalQuality,
    efficiency,
    riskMetrics,
    recommendation: generateStrategyRecommendation(signalQuality, efficiency, riskMetrics)
  }
}

// 辅助函数
export const calculateAvgHoldingPeriod = (trades) => {
  const pairs = []
  let buyTrade = null
  
  for (const trade of trades) {
    if (trade.type === 'buy') {
      buyTrade = trade
    } else if (trade.type === 'sell' && buyTrade) {
      const buyDate = new Date(buyTrade.date)
      const sellDate = new Date(trade.date)
      pairs.push((sellDate - buyDate) / (1000 * 60 * 60 * 24)) // 天数
      buyTrade = null
    }
  }
  
  return pairs.length > 0 ? pairs.reduce((a, b) => a + b, 0) / pairs.length : 0
}

export const calculateMaxConsecutive = (trades, isWin) => {
  let maxCount = 0
  let currentCount = 0
  
  for (const trade of trades) {
    const condition = isWin ? trade.profit > 0 : trade.profit <= 0
    if (condition) {
      currentCount++
      maxCount = Math.max(maxCount, currentCount)
    } else {
      currentCount = 0
    }
  }
  
  return maxCount
}

export const calculateMaxDrawdownFromCurve = (equityCurve) => {
  if (equityCurve.length === 0) return 0
  
  let maxEquity = equityCurve[0].equity
  let maxDrawdown = 0
  
  for (const point of equityCurve) {
    maxEquity = Math.max(maxEquity, point.equity)
    const drawdown = (maxEquity - point.equity) / maxEquity
    maxDrawdown = Math.max(maxDrawdown, drawdown)
  }
  
  return maxDrawdown * 100
}

export const calculateEquityVolatility = (equityCurve) => {
  if (equityCurve.length < 2) return 0
  
  const returns = []
  for (let i = 1; i < equityCurve.length; i++) {
    const ret = (equityCurve[i].equity - equityCurve[i-1].equity) / equityCurve[i-1].equity
    returns.push(ret)
  }
  
  const mean = returns.reduce((a, b) => a + b, 0) / returns.length
  const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length
  
  return Math.sqrt(variance) * 100
}

export const calculateRiskAdjustedReturn = (equityCurve) => {
  if (equityCurve.length === 0) return 0
  
  const totalReturn = (equityCurve[equityCurve.length - 1].equity - equityCurve[0].equity) / equityCurve[0].equity
  const volatility = calculateEquityVolatility(equityCurve) / 100
  
  return volatility > 0 ? totalReturn / volatility : 0
}

export const generateStrategyRecommendation = (signalQuality, efficiency, riskMetrics) => {
  const recommendations = []
  
  // 信号质量建议
  if (signalQuality.avgConfidence < 0.7) {
    recommendations.push('建议提高置信度阈值或调整特征权重')
  }
  
  if (signalQuality.totalSignals > 0 && signalQuality.weakSignals / signalQuality.totalSignals > 0.4) {
    recommendations.push('弱信号过多，考虑开启风险过滤器')
  }
  
  // 交易效率建议
  if (efficiency.profitableTradeRatio < 0.5) {
    recommendations.push('胜率较低，建议优化止损止盈参数')
  }
  
  if (efficiency.maxConsecutiveLosses > 5) {
    recommendations.push('连续亏损过多，建议开启动态仓位管理')
  }
  
  // 风险控制建议
  if (riskMetrics.maxDrawdown > 20) {
    recommendations.push('最大回撤过大，建议降低仓位或加强风险控制')
  }
  
  if (riskMetrics.volatility > 15) {
    recommendations.push('策略波动性较大，建议调整情绪指标权重')
  }
  
  return recommendations.length > 0 ? recommendations : ['策略表现良好，可继续使用']
}